﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;


namespace littleAdminHelper
{
    public partial class frm_main : Form
    {
        Dumper dumper;


        public frm_main()
        {
            InitializeComponent();
            try
            {
                loadConfiguration();
            }
            catch (Exception e)
            {
                MessageBox.Show("Opening Configuration File is not possible, Please check your Config File.");
            }

            try
            {
                loadWMIData();
            }
            catch (Exception e)
            {
                MessageBox.Show("Loading WMI Data failed.");
            }

            try
            {
                loadRegistryData();
            }
            catch (Exception e)
            {
                MessageBox.Show("Loading Registry Data failed.");
            }

            try
            {
                loadConnectionDetails();
            }
            catch (Exception e)
            {
                MessageBox.Show("Loading Connection Details failed.");
            }
           
        }

        private void fileItemRemoteHelpClick(object sender, EventArgs e)
        {
            script.openFileOrURL(ConfigurationManager.AppSettings.Get("remoteHelpUrl"));
        }

        private void helpButtonClick(object sender, EventArgs e)
        {
            script.openFileOrURL("https://littleadminhelper.codeplex.com/");
        }

        private void sendSupportMailClick(object sender, EventArgs e)
        {
            // creating an Instance of Mail to send mail via SMTP or mailto Command   
            Mail mail = new Mail();

            //script.openFileOrURL("mailto:" + ConfigurationManager.AppSettings.Get("SupportEmailAddress") +
            //"?subject=" + subject + "&body=" + body + "&Attachment=" + @dumper.getPath() + "\\" + @dumper.getFilename());


            // creating a Dump with all required Informations
            if (ConfigurationManager.AppSettings.Get("MailAttachementType")=="csv"){
                dumper = new dumpInfoToCsv();
            }else{
                dumper = new dumpInfoToTxt();
            }
            // dump ComputerConfig
            dumper.addText(wmi.getComputerInformations());

            // dump NetworkConfig
            dumper.addText(wmi.getNetworkConfig());

            // dump WMI Data
            try
            {
                for (int i = 0; ; i++)
                {
                    if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "WMIQueryEnable")))
                    {
                        dumper.addText(ConfigurationManager.AppSettings.Get(i + "WMIResultDescription") + ": " + wmi.getCustomValues(ConfigurationManager.AppSettings.Get(i + "WMIQueryDirectory"), ConfigurationManager.AppSettings.Get(i + "WMIQuery")));
                    }
                }
            }
            catch {}

            // dump Registry Data
            try
            {
                for (int i = 0; ; i++)
                {
                    if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "RegistryQueryEnable")))
                    {
                        if (registry.valueExists(ConfigurationManager.AppSettings.Get(i + "RegistryPath"), ConfigurationManager.AppSettings.Get(i + "RegistryValue")))
                        {
                            dumper.addText(ConfigurationManager.AppSettings.Get(i + "RegistryResultDescription") + ": " + registry.getValue(ConfigurationManager.AppSettings.Get(i + "RegistryPath"), ConfigurationManager.AppSettings.Get(i + "RegistryValue")));
                        }
                        else
                        {
                            dumper.addText(ConfigurationManager.AppSettings.Get(i+ "RegistryResultDescription") + ": " + "Key Not Available");
                        }
                    }
                }
            }catch (Exception ex){

            }




            dumper.addText(ConfigurationManager.AppSettings.Get("SupportEmailText"));
            dumper.dump();

            if (Boolean.Parse(ConfigurationManager.AppSettings.Get("MailAttachementsEnabled")))
            {
                
                mail.addAttachement(dumper.getPath() + "\\" + dumper.getFilename());
                mail.setAttachements_enabled(Boolean.Parse(ConfigurationManager.AppSettings.Get("MailAttachementsEnabled")));
            }else{
                mail.setMailText(mail.getMailtext() + dumper.toString());
            }

            // adding required Informations to send Emails
            mail.setMailSubject(ConfigurationManager.AppSettings.Get("SupportEmailSubject").ToString());

            // Set variables which have to be replaced before Sending the Message
            String[] searches = { "%COMPUTERNAME%", "%USERNAME%", "%SYSDATE%" };
            String[] replaces = {wmi.getComputerName(),wmi.getUserName(),System.DateTime.Now.ToString()};

            // set add & Replace Values for Email Text and Subject
            mail.setReplaces(searches, replaces);
            mail.setMailserver(ConfigurationManager.AppSettings.Get("SmtpServer"));
            mail.setSenderAddress(ConfigurationManager.AppSettings.Get("SupportSenderaddress"));
            try
            {
                if (Boolean.Parse(ConfigurationManager.AppSettings.Get("SmtpAuthRequired")))
                {
                    mail.setSmtpAuthRequired(Boolean.Parse(ConfigurationManager.AppSettings.Get("SmtpAuthRequired")));
                    mail.setSmtpAuthUser(ConfigurationManager.AppSettings.Get("SmtpAuthUser"));
                    mail.setSmtpAuthPassword(SimpleCrypto.encrypt(ConfigurationManager.AppSettings.Get("SmtpAuthPassword")));
                    mail.setSSLEnable(true);
                    mail.sentMailSMTP(ConfigurationManager.AppSettings.Get("SupportEmailAddress"));
                }
                else
                {
                    throw new Exception();
                }
            }
            catch (Exception ex)
            {
                mail.sentmailMailto(ConfigurationManager.AppSettings.Get("SupportEmailAddress"));
               
            }
            
            
            
            
            
           
            


        

           
           





           
           
        }

        private void loadConfiguration()
        {
            // test XML REader Class
            //ReadXMLFile rxf = new ReadXMLFile(Environment.CurrentDirectory + "\\XMLLanguage.xml");


            // Simple Crypto for SMTP Auth Password
            //try
            //{
            //    if (!Boolean.Parse(ConfigurationManager.AppSettings.Get("SmtpAuthPasswordIsSecured")))
            //    {
            //        string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            //        string configFile = System.IO.Path.Combine(appPath, "littleAdminHelper.exe.config");
            //        ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
            //        configFileMap.ExeConfigFilename = configFile;



            //        System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

            //        // If Password is not encrypted
            //        // Encrypt
            //        config.AppSettings.Settings["SmtpAuthPasswordIsSecured"].Value = "True";
            //        config.AppSettings.Settings["SmtpAuthPassword"].Value = SimpleCrypto.decrypt(ConfigurationManager.AppSettings.Get("SmtpAuthPassword"));

            //        // write to Config File

            //        config.Save(ConfigurationSaveMode.Modified);

            //    }
            //}
            //catch (Exception e)
            //{
            //    MessageBox.Show("Error Decrypting Password");
            //}



            // create Main Menu Strip
            //ToolStripItem item =
            //menu_main.Items.Add(ConfigurationManager.AppSettings.Get("menuFileCaption"));


            ToolStripMenuItem menuRefresh = new ToolStripMenuItem(littleAdminHelper.Properties.Resources.arrow_refresh);
            menuRefresh.Click += new System.EventHandler(this.loadConfiguration);
            menu_main.Items.Add(menuRefresh);

            if (Boolean.Parse(ConfigurationManager.AppSettings.Get("MaildeliveryEnabled"))){
            ToolStripMenuItem menuSendSupportMail = new ToolStripMenuItem(littleAdminHelper.Properties.Resources.email_attach);
            menuSendSupportMail.Click += new System.EventHandler(this.sendSupportMailClick);
            menu_main.Items.Add(menuSendSupportMail);
            }

            ToolStripMenuItem menuSettings = new ToolStripMenuItem(littleAdminHelper.Properties.Resources.cog);
            menuSettings.Click += new System.EventHandler(this.showSettingsClick);
            menu_main.Items.Add(menuSettings);

            if (Boolean.Parse(ConfigurationManager.AppSettings.Get("remoteHelp")))
            {
                ToolStripMenuItem menuRemoteHelp = new ToolStripMenuItem(ConfigurationManager.AppSettings.Get("menuRemotehelpCaption"));
                menuRemoteHelp.Click += new System.EventHandler(this.fileItemRemoteHelpClick);
                menu_main.Items.Add(menuRemoteHelp);
            }
            // end Main Menu Strip

            // Custom Menu
            ToolStripMenuItem customMenu = new ToolStripMenuItem(ConfigurationManager.AppSettings.Get("customMenuCaption"));

            ToolStripMenuItem custom;
            // load Scripts
            try
            {
                for (int i = 0; ; i++)
                {
                    if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "ScriptShowInURLMenue")) && Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "ScriptEnable")))
                    {
                        custom = new ToolStripMenuItem(ConfigurationManager.AppSettings.Get(i + "ScriptURLMenuDescription"));
                        custom.Click += new EventHandler(this.menu_custom_scripts);
                        customMenu.DropDownItems.Add(custom);
                    }
                }

            }
            catch (Exception e)
            {
                
                //
            }
                // load Applications
            try
            {
                for (int i = 0; ; i++)
                {
                    if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "ApplicationEnable")))
                    {
                        custom = new ToolStripMenuItem(ConfigurationManager.AppSettings.Get(i + "ApplicationDescription"));
                        custom.Click += new EventHandler(this.menu_custom_application);
                        customMenu.DropDownItems.Add(custom);
                    }
                }

            }
            catch (Exception e)
            {
            }



            menu_main.Items.Add(customMenu);

            // Help Button
            ToolStripMenuItem menuHelp = new ToolStripMenuItem(ConfigurationManager.AppSettings.Get("menuHelpCaption"));
            menuHelp.Click += new System.EventHandler(this.helpButtonClick);
            menu_main.Items.Add(menuHelp);

           
            





            // Show Logo Yes/No
            if (Boolean.Parse(ConfigurationManager.AppSettings.Get("showLogo")) == false)
            {
                pic_logo.Visible = false;
                this.loadLogo();
            }
            else
            {
                pic_logo.Visible = true;
                this.loadLogo();
            }

            //Show ComputerInfo Yes/No
            if (Boolean.Parse(ConfigurationManager.AppSettings.Get("showComputerInfo")) == false)
            {
                txt_computerinfo.Visible = false;
                lbl_computerinfo.Visible = false;
            }
            else
            {
                txt_computerinfo.Visible = true;
                lbl_computerinfo.Visible = true;
            }

            //Show NetworkInfo Yes/No
            if (Boolean.Parse(ConfigurationManager.AppSettings.Get("showNetworkInfo")) == false)
            {
                txt_networkinfo.Visible = false;
                lbl_networkinfo.Visible = false;
            }
            else
            {
                txt_networkinfo.Visible = true;
                lbl_networkinfo.Visible = true;
            }

            lbl_computername.Text = ConfigurationManager.AppSettings.Get("labelComputernameCaption");
            lbl_internetconnection.Text = ConfigurationManager.AppSettings.Get("labelInternetConnectionCaption");
            // set Form Header
            //frm_main.ActiveForm.Text = ConfigurationManager.AppSettings.Get("AppName");

            lbl_networkinfo.Text = ConfigurationManager.AppSettings.Get("labelNetworkInfoCaption");
            lbl_computerinfo.Text = ConfigurationManager.AppSettings.Get("labelComputerInfoCaption");

            lbl_proxyserver.Text = ConfigurationManager.AppSettings.Get("labelProxyServerCaption");
            lbl_navigationhelp.Text = ConfigurationManager.AppSettings.Get("labelNavigationHelpCaption");

           
           


        }

        private void loadConfiguration(object sender, EventArgs e)
        {
            this.loadLogo();
            this.loadWMIData();
            this.loadConnectionDetails();
            this.loadRegistryData();
        }

        private void loadLogo()
        {
            try
            {
                Bitmap logo = new Bitmap(PathConversion.encodepath(ConfigurationManager.AppSettings.Get("logopath")));
                pic_logo.Image = logo;
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Displaying Logo is not possible");
            }
        }

        private void loadWMIData()
        {
            lbl_computernamewmi.Text = wmi.getComputerName();
            txt_networkinfo.Text = wmi.getNetworkConfig();
            txt_computerinfo.Text = wmi.getComputerInformations();

            // Custom WMI Querys
            //MessageBox.Show(wmi.getCustomValues("root\\CIMV2", "SELECT Caption FROM Win32_BootConfiguration"));

            try
            {
                String wmioutput = "";
                for (int i = 0; ; i++)
                {
                    // if WMIQuery is Enabled
                    if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "WMIQueryEnable")))
                    {
                        wmioutput = wmi.getCustomValues(ConfigurationManager.AppSettings.Get(i + "WMIQueryDirectory"), ConfigurationManager.AppSettings.Get(i + "WMIQuery"));
                        if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "WMIShowinComputerInfo")))
                        {
                            txt_computerinfo.Text += "\r\n" + ConfigurationManager.AppSettings.Get(i + "WMIResultDescription") + ":\t\t" + wmioutput;
                        }
                        if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "WMIShowinNetworkInfo")))
                        {

                            txt_networkinfo.Text += "\r\n" + ConfigurationManager.AppSettings.Get(i + "WMIResultDescription") + ":\t\t" + wmioutput;
                        }

                    }
                }
            }
            catch (Exception ex)
            {
            }


            
        }

        private void loadRegistryData() {
            String value = "";
            String description = "";

            // load ProxyServer Data
            try
            {
                Bitmap ok = new Bitmap(littleAdminHelper.Properties.Resources.tick);
                Bitmap nok = new Bitmap(littleAdminHelper.Properties.Resources.exclamation);


                if (registry.getValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\", "ProxyEnable") == ConfigurationManager.AppSettings.Get("registryEntryProxyServerStatusForOk"))
                {
                    pic_proxy.Image = (Image)ok;
                }
                else
                {
                    pic_proxy.Image = (Image)nok;
                }

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                MessageBox.Show(e.StackTrace);
            }

            // load Custom Registry Informations

            try
            {
                for (int i = 0; ; i++)
                {
                    if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "RegistryQueryEnable")))
                    {
                        // query is Enabled
                        description = ConfigurationManager.AppSettings.Get(i + "RegistryResultDescription");
                        if (registry.valueExists(ConfigurationManager.AppSettings.Get(i + "RegistryPath"),ConfigurationManager.AppSettings.Get(i+"RegistryValue")))
                        {
                            value = registry.getValue(ConfigurationManager.AppSettings.Get(i + "RegistryPath"), ConfigurationManager.AppSettings.Get(i + "RegistryValue"));
                            description = ConfigurationManager.AppSettings.Get(i + "RegistryResultDescription");
                            if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "RegistryShowInComputerInfo")))
                            {
                                txt_computerinfo.Text += description + ": \t" + value + "\r\n";
                            }
                            else if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "RegistryShowInNetworkInfo")))
                            {
                                txt_networkinfo.Text += description + ": \t" + value + "\r\n";
                            }

                        }
                        else
                        {
                            if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "RegistryShowInComputerInfo")))
                            {
                                txt_computerinfo.Text += description + ": \tKey is not Available\r\n";
                            }
                            else if (Boolean.Parse(ConfigurationManager.AppSettings.Get(i + "RegistryShowInNetworkInfo")))
                            {
                                txt_networkinfo.Text += description + ": \tKey is not Available\r\n";
                            }
                        }


                    }
                    else
                    {
                        // not Enabled
                    }
                }


            }
            catch (Exception e)
            {

            }



          
        
        }
        
        private void loadConnectionDetails()
        {
            Image ok = (Image)littleAdminHelper.Properties.Resources.tick;
            Image nok = (Image)littleAdminHelper.Properties.Resources.exclamation;

            if(internetconnection.checkConnection("www.google.de")){
                pic_internetconnection.Image=ok;
            }else{
                pic_internetconnection.Image=nok;
            }

            if (internetconnection.checkConnection("www.blablaadfadadafdfadaf.com32"))
            {
                pic_navigation.Image = nok;
            }
            else
            {
                pic_navigation.Image = ok;
            }


        }

        private void showSettingsClick(object sender, EventArgs e)
        {
            Form settings = new frm_settings();
            settings.Show();
        }

        private void menu_custom_scripts(object sender, EventArgs e)
        {
           
            try{
            for (int i=0; ; i++)
            {
                if (sender.ToString().Equals(ConfigurationManager.AppSettings.Get(i + "ScriptURLMenuDescription")))
                {
                    script.openFileOrURL(ConfigurationManager.AppSettings.Get(i + "Scriptsrc"));
                }
            }
            }catch (Exception ex){
                MessageBox.Show("Scriptfile Execution failed");
            }
            
        }

        private void menu_custom_application(object sender, EventArgs e)
        {
            try{
            for (int i=0; i<7 ; i++)
            {
                if (sender.ToString().Equals(ConfigurationManager.AppSettings.Get(i + "ApplicationDescription")))
                {

                    
                        script.openFileOrURL(ConfigurationManager.AppSettings.Get(i + "ApplicationSrc"));
                    break;
                    
                }
            }
            }catch (Exception ex){
                MessageBox.Show("Application Execution failed");
            }
            
        }

        private void frm_main_Load(object sender, EventArgs e)
        {

        }

    }
}
